﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;

using RTGS.Library.Entities.UserManagement;
using RTGS.Library.DataAccess.UserManagement;

namespace RTGS.Web.support
{
    public class Membership 
    {
        sysTUserRepo userDal = null;

        static string KemenhubConnectionString;

        public Membership(string connectionString)
        {
            KemenhubConnectionString = connectionString;
        }

        public bool ValidateUser(string username, string password, out sysTUser user, out string errorMessage)
        {
            userDal = new sysTUserRepo(KemenhubConnectionString);

            return userDal.ValidateUser(username, password, out user, out errorMessage);

        }

        public List<sysTMenu> GetMenusByRoleIDs(List<int> roleIds)
        {
            sysTMenuRightsRepo menuRightsDal = new sysTMenuRightsRepo(KemenhubConnectionString);

            var menuIds = (from m in menuRightsDal.GetList()
                            where (roleIds.Contains(m.roleId))
                            select m.menuId).Distinct();                        

            sysTMenuRepo menuDal = new sysTMenuRepo(KemenhubConnectionString);
 
            List<sysTMenu> menus = menuDal.GetList().Where(m => menuIds.Contains(m.menuId)).ToList();

            return menus;
        }

        public List<sysTUserRole> GetRoles(int userId)
        {
            sysTUserRoleRepo userRoleDal = new sysTUserRoleRepo(KemenhubConnectionString);
            List<sysTUserRole> userRoles = userRoleDal.GetList().Where(x => x.userId == userId).ToList();

            return userRoles;
        }

        public bool IsAdmin(int userId)
        {
            bool result = false;

            sysTRoleRepo roleDal = new sysTRoleRepo(KemenhubConnectionString);

            sysTUserRoleRepo userRoleDal = new sysTUserRoleRepo(KemenhubConnectionString);

            var role = roleDal.GetList().Find(x => x.roleName.ToLower().Trim() == "administrator");

            if (role != null)
            {
                userRoleDal.GetList().Where(x => x.userId == userId);


            }

            return result;
        }
    }

}